package explore.hxx.binarytree.self;

import explore.hxx.binarytree.dependence.Node;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: waxijiang
 * @Date: 2021/6/4
 */
public class FillRightNodePointer2 {
    public Node connect(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if (root != null) {
            queue.add(root);
        }

        while (!queue.isEmpty()) {
            int levelCount = queue.size();
            Node pre = null;
            for (int i = 0; i < levelCount; i++) {
                Node node = queue.poll();
                if (pre != null) {
                    pre.next = node;
                }
                pre = node;

                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return root;
    }
}
